package com.yingpai.fitness.dvp_2_0.main.activity.shop;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.address.AddAddressActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.address.AddressSelectActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.assmble.AssmbleActivity;
import com.yingpai.fitness.dvp_2_0.main.bean.CouponOrderUseBean;
import com.yingpai.fitness.dvp_2_0.main.bean.assmble.AssmbleDetailBean;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ChongZhiDingDanEntiy;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ZfbChongZhiEntity;
import com.yingpai.fitness.dvp_2_0.main.callback.WechatCallBack;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.PayUtil;
import com.yingpai.fitness.dvp_2_0.main.util.WechatLoginUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.CreateOrderBean;
import com.yingpai.fitness.entity.ReadyOrderBean;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;
import com.yingpai.fitness.entity.address.AddressBean;
import com.yingpai.fitness.entity.wx.TokenBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PurchaseOrderActivity extends CommonActivity implements PayUtil.codeResultClickInterface, WechatCallBack {


    @BindView(R.id.wechat_layout)
    RelativeLayout mlayout_wechat;
    @BindView(R.id.alipay_layout)
    RelativeLayout mlayout_alipay;
    @BindView(R.id.add_address)
    LinearLayout addAddress;
    @BindView(R.id.consigneeNameTv)
    TextView consigneeNameTv;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.shop_num)
    TextView shopNum;
    @BindView(R.id.order_num)
    TextView orderNum;
    @BindView(R.id.ordingMsgLv)
    XListView ordingMsgLv;
    @BindView(R.id.sumPriceTv)
    TextView sumPriceTv;
    @BindView(R.id.unit)
    TextView unit;
    @BindView(R.id.freightTv)
    TextView freightTv;
    @BindView(R.id.buyMessageEt)
    EditText buyMessageEt;
    @BindView(R.id.count)
    TextView count;
    @BindView(R.id.weChatPayCb)
    CheckBox weChatPayCb;
    @BindView(R.id.aLiPayCb)
    CheckBox aLiPayCb;
    @BindView(R.id.nested_scroll_view)
    NestedScrollView nestedScrollView;
    @BindView(R.id.moneyTv)
    TextView moneyTv;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.address_ll)
    LinearLayout address_ll;
    @BindView(R.id.rl_address)
    LinearLayout rl_address;
    @BindView(R.id.coupon)
    TextView coupon;
    private TokenBean tokenBean;
    private QuickAdapter<ReadyOrderBean.MapBean.ShoppingCartDTOListBean> quickAdapter;

    private int source;
    private String merchandiseId;
    private String merchandiseJson;
    private int purchaseAmount;
    private String tag = Constant.WECHAT;;
    private String shoppingCartIds = "";
    private int addreddId;//地址id
    private ReadyOrderBean mReadyOrderBean;
    private CreateOrderBean mCreateOrderBean;
    private DecimalFormat df = new DecimalFormat("######.###");
    private String myTicketId = "";
    private int mPosition;
    private String flag = "";
    private String joinId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.purchase_order_activity);
    }

    @Override
    protected void initView() {
        setTitle("确认订单");
        EventBus.getDefault().register(this);
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            source = bundle.getInt("source", -1);
            merchandiseId = bundle.getString("merchandiseId", "");
            merchandiseJson = bundle.getString("merchandiseJson");
            purchaseAmount = bundle.getInt("purchaseAmount", 0);
            shoppingCartIds = bundle.getString("shoppingCartIds");
            flag = bundle.getString("flag", "");
            joinId = bundle.getString("groupBookId");
        }
        final int startColor = ContextCompat.getColor(this, R.color.normal_status);
        final int endColor = ContextCompat.getColor(this, R.color.colorNavigation);

        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int headHeight = address_ll.getHeight();
                int scrollDistance = Math.min(scrollY, headHeight);
                float fraction = (float) scrollDistance / (float) headHeight;

//                setToolbarStatusBarAlpha(evaluate(fraction, startColor, endColor),titleBar);
                setNavigationViewColor(evaluate(fraction, startColor, endColor));
            }
        });

        buyMessageEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                PurchaseOrderActivity.this.count.setText(buyMessageEt.getText().toString().length() + "/" + 100);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        quickAdapter = new QuickAdapter<ReadyOrderBean.MapBean.ShoppingCartDTOListBean>(this, R.layout.item_ready_order) {
            @Override
            protected void convert(BaseAdapterHelper helper, ReadyOrderBean.MapBean.ShoppingCartDTOListBean item) {
                helper.setText(R.id.title, item.getMerchandiseName());
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrl())
                        .placeholder(R.mipmap.default_big_bg)
                        .into(photo);

                List<ShopDetailMcipChildBean> propertyList = GsonUtil.jsonToList(item.getPropertyValue(), ShopDetailMcipChildBean.class);
                String s = "";
                for (int i = 0; i < propertyList.size(); i++) {
                    if (i == propertyList.size() - 1) {
                        s = s + propertyList.get(i).getPropertyValue();
                    } else {
                        s = s + propertyList.get(i).getPropertyValue() + "；";
                    }
                }

                helper.setText(R.id.count, "数量：X" + item.getQuantity() + "；" + s);

                if(flag.equals("assmble")||flag.equals("join")){
                    helper.setText(R.id.price, "￥" + df.format(item.getPrice()));
                }else{
                    helper.setText(R.id.price, "￥" + df.format(item.getPrice() / 100));
                }

            }
        };
        ordingMsgLv.setAdapter(quickAdapter);
        ordingMsgLv.setFocusable(false);
    }


    @Override
    protected void initData() {
        showDialog(this, null);
        if (source == 1) {
            HttpParams httpParams = new HttpParams();
            httpParams.put("customerId", tokenBean.getId());
            httpParams.put("source", source);
            httpParams.put("merchandiseId", merchandiseId);
            httpParams.put("merchandiseJson", merchandiseJson);
            httpParams.put("purchaseAmount", purchaseAmount);
            httpParams.put("shoppingCartIds", "");
            finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.ORDER_DETAIL, httpParams, Url.ORDER_DETAIL, new Callback<ReadyOrderBean>() {
                @Override
                public void onSuccess(ReadyOrderBean readyOrderBean) {
                    if (readyOrderBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                        mReadyOrderBean = readyOrderBean;
                        if (readyOrderBean.getMap().getAddresses() == null) {
                            consigneeNameTv.setText("");
                            addAddress.setVisibility(View.VISIBLE);
                            rl_address.setVisibility(View.GONE);
                        } else {
                            addAddress.setVisibility(View.GONE);
                            rl_address.setVisibility(View.VISIBLE);
                            consigneeNameTv.setText(readyOrderBean.getMap().getAddresses().getReceiverName() + " / " + readyOrderBean.getMap().getAddresses().getReceiverPhoneNo());
                            address.setText(readyOrderBean.getMap().getAddresses().getAddress());
                            addreddId = readyOrderBean.getMap().getAddresses().getId();
                        }

                        shopNum.setText(readyOrderBean.getMap().getPurchaseAmount() + "件商品");
                        orderNum.setText("订单号：" + readyOrderBean.getMap().getOrderCode());

                        Collections.reverse(readyOrderBean.getMap().getPropertySet());

                        quickAdapter.clear();
                        quickAdapter.addAll(readyOrderBean.getMap().getShoppingCartDTOList());
                        quickAdapter.notifyDataSetChanged();

                        sumPriceTv.setText("￥" + df.format(readyOrderBean.getMap().getMerchandisePrice() / 100));
                        freightTv.setText("￥" + df.format(readyOrderBean.getMap().getPostPrice() / 100));
                        money.setText("" + df.format((readyOrderBean.getMap().getMerchandisePrice() + readyOrderBean.getMap().getPostPrice()) / 100));

                    } else {
                        showToast(readyOrderBean.getMsg());
                    }
                    dismissDialog();
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dismissDialog();
                }
            });
        } else if (source == 2) {
            HttpParams httpParams = new HttpParams();
            httpParams.put("customerId", tokenBean.getId());
            httpParams.put("source", source);
            httpParams.put("shoppingCartIds", shoppingCartIds);
            finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.ORDER_DETAIL, httpParams, Url.ORDER_DETAIL, new Callback<ReadyOrderBean>() {
                @Override
                public void onSuccess(ReadyOrderBean readyOrderBean) {
                    if (readyOrderBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                        mReadyOrderBean = readyOrderBean;
                        if (readyOrderBean.getMap().getAddresses() == null) {
                            consigneeNameTv.setText("");
                            addAddress.setVisibility(View.VISIBLE);
                            rl_address.setVisibility(View.GONE);
                        } else {
                            addAddress.setVisibility(View.GONE);
                            rl_address.setVisibility(View.VISIBLE);
                            consigneeNameTv.setText(readyOrderBean.getMap().getAddresses().getReceiverName() + " / " + readyOrderBean.getMap().getAddresses().getReceiverPhoneNo());
                            address.setText(readyOrderBean.getMap().getAddresses().getAddress());
                            addreddId = readyOrderBean.getMap().getAddresses().getId();
                        }

                        shopNum.setText(readyOrderBean.getMap().getPurchaseAmount() + "件商品");
                        orderNum.setText("订单号：" + readyOrderBean.getMap().getOrderCode());

                        Collections.reverse(readyOrderBean.getMap().getPropertySet());

                        quickAdapter.clear();
                        quickAdapter.addAll(readyOrderBean.getMap().getShoppingCartDTOList());
                        quickAdapter.notifyDataSetChanged();

                        sumPriceTv.setText("￥" + df.format(readyOrderBean.getMap().getMerchandisePrice() / 100));
                        freightTv.setText("￥" + df.format(readyOrderBean.getMap().getPostPrice() / 100));
                        money.setText("" + df.format((readyOrderBean.getMap().getMerchandisePrice() + readyOrderBean.getMap().getPostPrice()) / 100));

                    } else {
                        showToast(readyOrderBean.getMsg());
                    }
                    dismissDialog();
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dismissDialog();
                }
            });
        } else {
            if (flag.equals("assmble")) {
                HashMap<String, Object> httpParams = new HashMap();
                httpParams.put("id", merchandiseId);
                httpParams.put("merchandiseJson", merchandiseJson);
                httpParams.put("purchaseAmount", purchaseAmount);
                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_AND_JOIN_ORDER, httpParams, Url.ASSMBLE_AND_JOIN_ORDER, new Callback<ReadyOrderBean>() {
                    @Override
                    public void onSuccess(ReadyOrderBean readyOrderBean) {
                        if (readyOrderBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            mReadyOrderBean = readyOrderBean;
                            if (readyOrderBean.getMap().getAddresses() == null) {
                                consigneeNameTv.setText("");
                                addAddress.setVisibility(View.VISIBLE);
                                rl_address.setVisibility(View.GONE);
                            } else {
                                addAddress.setVisibility(View.GONE);
                                rl_address.setVisibility(View.VISIBLE);
                                consigneeNameTv.setText(readyOrderBean.getMap().getAddresses().getReceiverName() + " / " + readyOrderBean.getMap().getAddresses().getReceiverPhoneNo());
                                address.setText(readyOrderBean.getMap().getAddresses().getAddress());
                                addreddId = readyOrderBean.getMap().getAddresses().getId();
                            }

                            shopNum.setText(readyOrderBean.getMap().getPurchaseAmount() + "件商品");
                            orderNum.setText("订单号：" + readyOrderBean.getMap().getOrderCode());

                            Collections.reverse(readyOrderBean.getMap().getPropertySet());

                            quickAdapter.clear();
                            quickAdapter.addAll(readyOrderBean.getMap().getShoppingCartDTOList());
                            quickAdapter.notifyDataSetChanged();

                            sumPriceTv.setText("￥" + df.format(readyOrderBean.getMap().getMerchandisePrice()));
                            freightTv.setText("￥" + df.format(readyOrderBean.getMap().getPostPrice()));
                            money.setText("" + df.format((readyOrderBean.getMap().getMerchandisePrice() + readyOrderBean.getMap().getPostPrice())));
                        } else {
                            showToast(readyOrderBean.getMsg());
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
            } else if (flag.equals("join")) {
                HashMap<String, Object> httpParams = new HashMap();
                httpParams.put("id", merchandiseId);
                httpParams.put("groupBookId", joinId);
                httpParams.put("merchandiseJson", merchandiseJson);
                httpParams.put("purchaseAmount", purchaseAmount);
                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_AND_JOIN_ORDER, httpParams, Url.ASSMBLE_AND_JOIN_ORDER, new Callback<ReadyOrderBean>() {
                    @Override
                    public void onSuccess(ReadyOrderBean readyOrderBean) {
                        if (readyOrderBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            mReadyOrderBean = readyOrderBean;
                            if (readyOrderBean.getMap().getAddresses() == null) {
                                consigneeNameTv.setText("");
                                addAddress.setVisibility(View.VISIBLE);
                                rl_address.setVisibility(View.GONE);
                            } else {
                                addAddress.setVisibility(View.GONE);
                                rl_address.setVisibility(View.VISIBLE);
                                consigneeNameTv.setText(readyOrderBean.getMap().getAddresses().getReceiverName() + " / " + readyOrderBean.getMap().getAddresses().getReceiverPhoneNo());
                                address.setText(readyOrderBean.getMap().getAddresses().getAddress());
                                addreddId = readyOrderBean.getMap().getAddresses().getId();
                            }

                            shopNum.setText(readyOrderBean.getMap().getPurchaseAmount() + "件商品");
                            orderNum.setText("订单号：" + readyOrderBean.getMap().getOrderCode());

                            Collections.reverse(readyOrderBean.getMap().getPropertySet());

                            quickAdapter.clear();
                            quickAdapter.addAll(readyOrderBean.getMap().getShoppingCartDTOList());
                            quickAdapter.notifyDataSetChanged();

                            sumPriceTv.setText("￥" + df.format(readyOrderBean.getMap().getMerchandisePrice()));
                            freightTv.setText("￥" + df.format(readyOrderBean.getMap().getPostPrice()));
                            money.setText("" + df.format((readyOrderBean.getMap().getMerchandisePrice() + readyOrderBean.getMap().getPostPrice())));
                        } else {
                            showToast(readyOrderBean.getMsg());
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
            }
        }


    }

    private void choicePay() {
        if (tag.equals(Constant.ALIPAY)) {
            if (flag.equals("assmble") || flag.equals("join")) {
                HashMap<String, Object> httpParams = new HashMap();
                httpParams.put("orderId", mCreateOrderBean.getData().getId());
                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_SUER_OEDER_ALIPAY, httpParams, Url.ASSMBLE_SUER_OEDER_ALIPAY, new Callback<ZfbChongZhiEntity>() {
                    @Override
                    public void onSuccess(ZfbChongZhiEntity zfbChongZhiEntity) {
                        if (zfbChongZhiEntity.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            PayUtil.zfbpay(PurchaseOrderActivity.this, PurchaseOrderActivity.this, zfbChongZhiEntity.getMap().getResponse());
                        } else {
                            showToast(zfbChongZhiEntity.getMsg() + "");
                        }
                    }
                });
            } else {
                HttpParams httpParams = new HttpParams();
                httpParams.put("id", mCreateOrderBean.getData().getId());
                httpParams.put("customerId", tokenBean.getId());
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_ALI_PAY, httpParams, Url.SHOP_ALI_PAY, new Callback<ZfbChongZhiEntity>() {
                    @Override
                    public void onSuccess(ZfbChongZhiEntity zfbChongZhiEntity) {
                        if (zfbChongZhiEntity.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            PayUtil.zfbpay(PurchaseOrderActivity.this, PurchaseOrderActivity.this, zfbChongZhiEntity.getMap().getResponse());
                        } else {
                            showToast(zfbChongZhiEntity.getMsg() + "");
                        }
                    }
                });
            }
        } else if (tag.equals(Constant.WECHAT)) {
            if (flag.equals("assmble") || flag.equals("join")) {
                HashMap<String, Object> httpParams = new HashMap();
                httpParams.put("orderId", mCreateOrderBean.getData().getId());
                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_SUER_ORDER_WECHAT, httpParams, Url.ASSMBLE_SUER_ORDER_WECHAT, new Callback<ChongZhiDingDanEntiy>() {
                    @Override
                    public void onSuccess(ChongZhiDingDanEntiy chongZhiDingDanEntiy) {
                        if (chongZhiDingDanEntiy.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            WechatLoginUtil.getInstance().setWechatCallBack(PurchaseOrderActivity.this);
                            PayUtil.wxpay(getApplicationContext(), chongZhiDingDanEntiy.getMap().getResponse().getAppid(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getPartnerid(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getPrepayid(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getNoncestr(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getTimestamp() + "",
                                    chongZhiDingDanEntiy.getMap().getResponse().getSign());
                        } else {
                            showToast(chongZhiDingDanEntiy.getMsg());
                        }
                    }
                });
            } else {
                HttpParams httpParams = new HttpParams();
                httpParams.put("id", mCreateOrderBean.getData().getId());
                httpParams.put("customerId", tokenBean.getId());
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_WECHAT_PAY, httpParams, Url.SHOP_WECHAT_PAY, new Callback<ChongZhiDingDanEntiy>() {
                    @Override
                    public void onSuccess(ChongZhiDingDanEntiy chongZhiDingDanEntiy) {
                        if (chongZhiDingDanEntiy.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            WechatLoginUtil.getInstance().setWechatCallBack(PurchaseOrderActivity.this);
                            PayUtil.wxpay(getApplicationContext(), chongZhiDingDanEntiy.getMap().getResponse().getAppid(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getPartnerid(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getPrepayid(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getNoncestr(),
                                    chongZhiDingDanEntiy.getMap().getResponse().getTimestamp() + "",
                                    chongZhiDingDanEntiy.getMap().getResponse().getSign());
                        } else {
                            showToast(chongZhiDingDanEntiy.getMsg());
                        }
                    }
                });
            }
        } else {
            showToast("请选择支付方式");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void OnMessageEvent(AddressBean.MapBean.AddressesBean bean) {
        addAddress.setVisibility(View.GONE);
        rl_address.setVisibility(View.VISIBLE);
        consigneeNameTv.setText(bean.getReceiverName() + " / " + bean.getReceiverPhoneNo());
        address.setText(bean.getAddress());
        addreddId = bean.getId();
    }


    private void showSuccessDialog() {
        LayoutInflater mInflater = LayoutInflater.from(this);
        LinearLayout dialog_pay_success = (LinearLayout) mInflater.inflate(R.layout.dialog_shop_pay_success, null);
        Dialog dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();

        dialog_pay_success.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        dialog.show();
        dialog.setContentView(dialog_pay_success);
    }

    private void showFaileDialog() {
        LayoutInflater mInflater = LayoutInflater.from(this);
        LinearLayout dialog_pay_faile = (LinearLayout) mInflater.inflate(R.layout.dialog_pay_faile, null);
        Dialog dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();
        dialog.show();
        dialog.setContentView(dialog_pay_faile);
    }

    @Override
    public void ZFBSuccess(String code) {
        dismissDialog();
        if (flag.equals("assmble") || flag.equals("join")) {
            HashMap<String, Object> httpParams = new HashMap();
            httpParams.put("orderId", mCreateOrderBean.getData().getId());
            httpParams.put("payMode", Constant.NUM_1 + "");
            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_ORDER_NOTIFY, httpParams, Url.ASSMBLE_ORDER_NOTIFY, new Callback<AssmbleDetailBean>() {
                @Override
                public void onSuccess(AssmbleDetailBean assmbleDetailBean) {
                    if (assmbleDetailBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("assmbleDetailBean", assmbleDetailBean);
                        bundle.putString("flag", flag);
                        startFinishActivity(AssmbleActivity.class, bundle);
                    } else {
                        showToast(assmbleDetailBean.getMessage() + "");
                    }
                }

                @Override
                public void onError(Response response) {
                    super.onError(response);
                    showToast("网络异常");
                }
            });
        } else {
            HttpParams httpParams = new HttpParams();
            httpParams.put("customerId", tokenBean.getId());
            httpParams.put("orderId", mCreateOrderBean.getData().getId());
            httpParams.put("payMode", Constant.NUM_1 + "");
            finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_NOTIFY_PAY, httpParams, Url.SHOP_NOTIFY_PAY, new Callback<BaseResponse>() {
                @Override
                public void onSuccess(BaseResponse baseResponse) {
                    if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                        showSuccessDialog();
                    } else {
                        showFaileDialog();
                    }
                }

                @Override
                public void onError(Response response) {
                    super.onError(response);
                    showFaileDialog();
                }
            });
        }
    }

    @Override
    public void ZFBFail(String code) {
        dismissDialog();
        showFaileDialog();
    }

    @Override
    public void ZFBResultQueRen(String code) {

    }


    @Override
    public void callBack(BaseResp baseResp) {
        dismissDialog();
        if(baseResp.errCode != BaseResp.ErrCode.ERR_OK){
            return;
        }
        if (flag.equals("assmble") || flag.equals("join")) {
            HashMap<String, Object> httpParams = new HashMap();
            httpParams.put("orderId", mCreateOrderBean.getData().getId());
            httpParams.put("payMode", Constant.NUM_2 + "");
            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_ORDER_NOTIFY, httpParams, Url.ASSMBLE_ORDER_NOTIFY, new Callback<AssmbleDetailBean>() {
                @Override
                public void onSuccess(AssmbleDetailBean assmbleDetailBean) {
                    if (assmbleDetailBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("assmbleDetailBean", assmbleDetailBean);
                        bundle.putString("flag", flag);
                        startFinishActivity(AssmbleActivity.class, bundle);
                    } else {
                        showToast(assmbleDetailBean.getMessage() + "");
                    }
                }

                @Override
                public void onError(Response response) {
                    super.onError(response);
                    showToast("网络异常");
                }

            });
        } else {
            HttpParams httpParams = new HttpParams();
            httpParams.put("customerId", tokenBean.getId());
            httpParams.put("orderId", mCreateOrderBean.getData().getId());
            httpParams.put("payMode", Constant.NUM_2 + "");
            finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_NOTIFY_PAY, httpParams, Url.SHOP_NOTIFY_PAY, new Callback<BaseResponse>() {
                @Override
                public void onSuccess(BaseResponse baseResponse) {
                    if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                        showSuccessDialog();
                    } else {
                        showFaileDialog();
                    }

                }

                @Override
                public void onError(Response response) {
                    super.onError(response);
                    showFaileDialog();
                }

            });
        }
    }

    @Override
    @OnClick({R.id.add_address, R.id.rl_address, R.id.weChatPayCb, R.id.aLiPayCb, R.id.ordingOkBtn, R.id.coupon ,
            R.id.wechat_layout,R.id.alipay_layout})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.wechat_layout:
                weChatPayCb.performClick();
                aLiPayCb.setChecked(false);
                tag = Constant.WECHAT;
                break;
            case R.id.alipay_layout:
                aLiPayCb.performClick();
                weChatPayCb.setChecked(false);
                tag = Constant.ALIPAY;
                break;
            case R.id.coupon:
                if (flag.equals("assmble") || flag.equals("join")) {
                    showToast("拼团商品不参与优惠活动");
                } else {
                    DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_coupon);
                    View dialog_select_reason = DialogUtil.getInstance().dialog_bottom_layout;
                    ListView listView = dialog_select_reason.findViewById(R.id.listview);
                    final QuickAdapter<CouponOrderUseBean.DataBean.TicketsBean> quickAdapter =
                            new QuickAdapter<CouponOrderUseBean.DataBean.TicketsBean>(this, R.layout.item_coupon) {
                                @Override
                                protected void convert(BaseAdapterHelper helper, CouponOrderUseBean.DataBean.TicketsBean item) {
                                    TextView name = helper.getView(R.id.name);
                                    ImageView select = helper.getView(R.id.select);
                                    if (item.getIsUsable().equals("1")) {
                                        helper.setText(R.id.name, "满" + df.format(Double.parseDouble(item.getFull()) / 100) + "减" + df.format(Double.parseDouble(item.getMinus()) / 100));
                                    } else if (item.getIsUsable().equals("0")) {
                                        helper.setText(R.id.name, "满" + df.format(Double.parseDouble(item.getFull()) / 100) + "减" + df.format(Double.parseDouble(item.getMinus()) / 100) + "(不可用)");
                                    } else {
                                        helper.setText(R.id.name, "不使用");
                                    }
                                    if (item.isSelect()) {
                                        name.setTextColor(getResources().getColor(R.color.common_color));
                                        select.setImageResource(R.mipmap.icon_shop_cart_press);
                                    } else {
                                        name.setTextColor(getResources().getColor(R.color.calendar_textColor));
                                        select.setImageResource(R.mipmap.icon_shop_cart_normal);
                                    }
                                }
                            };
                    listView.setAdapter(quickAdapter);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if (quickAdapter.getItem(position).getIsUsable().equals("1")) {
                                for (int i = 0; i < quickAdapter.getCount(); i++) {
                                    quickAdapter.getItem(i).setSelect(false);
                                }
                                quickAdapter.getItem(position).setSelect(true);
                                quickAdapter.notifyDataSetChanged();
                                myTicketId = quickAdapter.getItem(position).getId();
                                mPosition = position;
                            } else if (quickAdapter.getItem(position).getIsUsable().equals("0")) {
                                showToast("还不满足条件哦，请继续加油");
                            } else {
                                for (int i = 0; i < quickAdapter.getCount(); i++) {
                                    quickAdapter.getItem(i).setSelect(false);
                                }
                                quickAdapter.getItem(position).setSelect(true);
                                quickAdapter.notifyDataSetChanged();
                                myTicketId = "";
                                mPosition = position;
                            }

                        }
                    });

                    dialog_select_reason.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUtil.getInstance().dialog_bottom.dismiss();
                            if (quickAdapter.getItem(mPosition).getIsUsable().equals("1")) {
                                coupon.setText("- ￥" + Integer.parseInt(quickAdapter.getItem(mPosition).getMinus()) / 100);
                                money.setText(df.format((mReadyOrderBean.getMap().getMerchandisePrice() + mReadyOrderBean.getMap().getPostPrice() - Integer.parseInt(quickAdapter.getItem(mPosition).getMinus())) / 100));
                            } else {
                                coupon.setText("不使用");
                            }

                        }
                    });
                    showDialog(this, null);
                    HashMap<String, Object> params = new HashMap<>();
                    params.put("totalPrice", df.format(mReadyOrderBean.getMap().getMerchandisePrice()));
//                params.put("brandId","");
                    finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_COUPON_LIST_ORDER, params, Url.GET_COUPON_LIST_ORDER, new Callback<CouponOrderUseBean>() {
                        @Override
                        public void onSuccess(CouponOrderUseBean couponOrderUseBean) {
                            if (couponOrderUseBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                CouponOrderUseBean.DataBean.TicketsBean ticketsBean = new CouponOrderUseBean.DataBean.TicketsBean();
                                ticketsBean.setIsUsable("2");
                                couponOrderUseBean.getData().getTickets().add(ticketsBean);
                                quickAdapter.clear();
                                quickAdapter.addAll(couponOrderUseBean.getData().getTickets());
                                quickAdapter.notifyDataSetChanged();
                                mPosition = quickAdapter.getCount() - 1;
                            } else {
                                showToast(couponOrderUseBean.getMessage() + "");
                            }
                            dismissDialog();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                }

                break;
            case R.id.add_address:
                startActivity(AddAddressActivity.class);
                break;
            case R.id.rl_address:
                startActivity(AddressSelectActivity.class);
                break;
            case R.id.weChatPayCb:
                if (weChatPayCb.isChecked()) {
                    tag = Constant.WECHAT;
                    aLiPayCb.setChecked(false);
                } else {
                    tag = "";
                }
                break;
            case R.id.aLiPayCb:
                if (aLiPayCb.isChecked()) {
                    tag = Constant.ALIPAY;
                    weChatPayCb.setChecked(false);
                } else {
                    tag = "";
                }
                break;
            case R.id.ordingOkBtn:
                //从开始判断，避免没有选择支付方式，而去创建订单
                if (TextUtils.isEmpty(tag)) {
                    showToast("请选择支付方式");
                    return;
                }
                //判断地址
                if(addreddId==0){
                    showToast("请填写地址");
                    return;
                }
                if (flag.equals("assmble")||flag.equals("join")) {
                    showDialog(this, "支付中...");
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < mReadyOrderBean.getMap().getShoppingCartDTOList().size(); i++) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("mcipId", mReadyOrderBean.getMap().getShoppingCartDTOList().get(i).getMcipId());
                            jsonObject.put("purchaseAmount", mReadyOrderBean.getMap().getShoppingCartDTOList().get(i).getQuantity());
                            jsonArray.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    HashMap<String, Object> httpParams = new HashMap<>();
                    httpParams.put("mcipIdAndAmountJson", jsonArray.toString());
                    httpParams.put("distributionModeId", 1);
                    httpParams.put("distributionTimeId", 1);
                    httpParams.put("receiveAddress", addreddId);
                    httpParams.put("orderCode", mReadyOrderBean.getMap().getOrderCode());
                    httpParams.put("merchandiseGroupBookingId", merchandiseId);
                    if (flag.equals("join")) {
                        httpParams.put("groupBookId", joinId);
                    }
                    finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_SUER_ORDER, httpParams, Url.ASSMBLE_SUER_ORDER, new Callback<CreateOrderBean>() {
                        @Override
                        public void onSuccess(CreateOrderBean createOrderBean) {
                            dismissDialog();
                            mCreateOrderBean = createOrderBean;
                            if (createOrderBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                choicePay();
                            } else {
                                showToast(createOrderBean.getMessage());
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                } else {
                    showDialog(this, "支付中...");
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < mReadyOrderBean.getMap().getShoppingCartDTOList().size(); i++) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("mcipId", mReadyOrderBean.getMap().getShoppingCartDTOList().get(i).getMcipId());
                            jsonObject.put("purchaseAmount", mReadyOrderBean.getMap().getShoppingCartDTOList().get(i).getQuantity());
                            jsonArray.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    HashMap<String, Object> httpParams = new HashMap<>();
                    httpParams.put("mcipIdAndAmountJson", jsonArray.toString());
                    httpParams.put("distributionModeId", 1);
                    httpParams.put("distributionTimeId", 1);
                    httpParams.put("receiveAddress", addreddId);
                    httpParams.put("orderCode", mReadyOrderBean.getMap().getOrderCode());
                    if (!TextUtils.isEmpty(shoppingCartIds)) {
                        httpParams.put("shoppingCartIds", shoppingCartIds);
                    }
                    if (!TextUtils.isEmpty(myTicketId)) {
                        httpParams.put("myTicketId", myTicketId);
                    }
                    finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.CREATE_ORDER, httpParams, Url.CREATE_ORDER, new Callback<CreateOrderBean>() {
                        @Override
                        public void onSuccess(CreateOrderBean createOrderBean) {
                            dismissDialog();
                            mCreateOrderBean = createOrderBean;
                            if (createOrderBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                //订单生成，购物车的东西应该清零，去更新购物车
                                EventBus.getDefault().post(Constant.UPDATA_CART);
                                choicePay();
                            } else {
                                showToast(createOrderBean.getMessage());
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                }
                break;
        }
    }
}